const { app,ipcMain } = require('electron')
const puppeteer = require('puppeteer-core')
const Spider = require('../puppeteer/spider')
const douyinCommentSelector = require('../utils/douyinComment')
const {cookieStringToArray} = require("../utils/cookies_convert");
const {scrollContainer, scrollIntoView} = require("../puppeteer/scroll");
const PuppeteerWebview = require('../utils/puppeteer')

// 添加重试函数
async function connectWithRetry(maxRetries = 3, delay = 1000) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      console.log(`尝试连接到调试端口 (尝试 ${i + 1}/${maxRetries})...`)
      const browser = await puppeteer.connect({
        browserURL: 'http://localhost:9222',
        defaultViewport: null,
        ignoreHTTPSErrors: true
      })
      console.log('连接成功！')
      return browser
    } catch (error) {
      console.error(`连接失败 (尝试 ${i + 1}/${maxRetries}):`, error)
      if (i < maxRetries - 1) {
        console.log(`等待 ${delay}ms 后重试...`)
        await new Promise(resolve => setTimeout(resolve, delay))
      }
    }
  }
  throw new Error('连接失败，已达到最大重试次数')
}

ipcMain.handle('puppeteer:connect', async () => {
  try {
    const browser = await connectWithRetry()
    const pages = await browser.pages()
    return { success: true, data: { pageCount: pages.length } }
  } catch (error) {
    console.error('Puppeteer 连接错误:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('puppeteer:screenshot', async () => {
  try {
    const browser = await connectWithRetry()
    const pages = await browser.pages()
    const page = pages[0]
    await page.screenshot({ path: 'screenshot.png' })
    return { success: true, data: 'screenshot.png' }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('puppeteer:getWebview', async () => {
  console.log("获取webview");
  const spider = new Spider()
  await spider.connect_webview()

  await spider.goto()

  // try {
  //   const { success, page } = await spider.get_webview_page()
  //   if (success) {
  //     console.log("获取webview page:", page);
  //   } else {
  //     console.log("获取webview page 失败:", page);
  //   }
  // } catch (error) {
  //   console.log("获取webview page catch:", error);
  // }
})


ipcMain.handle('puppeteer:test111', async (event, args) => {
  const {webviewId} = args
  const spider = new Spider()
  // 根据指定webviewId找到对应webview页面进行连接
  const page = await spider.connect_webview(webviewId)
  if (!page) {
    return []
  }
  await page.goto("https://rebang.today/")
  let arr = []
  await page.waitForSelector('h2.text-base.multirow-ellipsis-2')
  console.log('h2.text-base.multirow-ellipsis-2元素加载完成');

  const scrollTimes = 6
  for (let i = 0; i < scrollTimes; i++) {
    // 滚动到页面底部
    await page.evaluate(() => {
      window.scrollTo(0, document.body.scrollHeight)
    })
    // 等待一段时间
    await new Promise(resolve => setTimeout(resolve, 3000))
  }

  let elementArray = await page.$$('h2.text-base.multirow-ellipsis-2')
  for (let element of elementArray) {
    // 获取元素的文本内容
    const text = await element.evaluate(ele => ele?.textContent)
    arr.push(text)
  }
  // console.log('获取元素文本内容完成', arr)
  return arr
})

ipcMain.handle('puppeteer:test222', async (event, args) => {
  const spider = new Spider()
  let {webviewId, cookies} = args
  let page
  let flag = 0
  let commentList = []
  if (cookies) {
    // cookiesArray = cookieStringToArray(cookies)
    page = await spider.connect_webview(webviewId, cookies)
  } else {
    page = await spider.connect_webview(webviewId)
  }

  // 根据指定webviewId找到对应webview页面进行连接
  if (!page) {
    return []
  }

  await page.goto("https://www.douyin.com/video/7459289381845650699")

  try {
    // 等待元素出现
    const commentListHandle = await page.waitForSelector(douyinCommentSelector.commentContain, { timeout: 5000 });

    // await scrollIntoView({page, selector: 'footer[data-e2e="page-footer"]', totalSeconds: 1})

    let result = await new Promise(resolve => {
      // 监听响应事件
      page.on('response', response => {
        // 查看所有请求地址
        // console.log('拦截到响应：', response.url());
        if (response.request().method() === 'OPTIONS') {
          return;
        }
        // 匹配所需数据的请求地址
        // if (response.url().indexOf('https://www-hj.douyin.com/aweme/v1/web/comment/list')!== -1) {
        if (response.url().indexOf('https://www.douyin.com/aweme/v1/web/comment/list/')!== -1) {
          // 获取数据并转为 json 格式
          let promise = response.json()
              .then(async (data) => {
                // todo 打印输出数据，或者是保存入库
                commentList.push(...data.comments);
                app.mainWindow.webContents.send('comment-list-update', JSON.stringify(data.comments))
                if (data.has_more && commentList.length <= 150) {
                  // 如果有数据 且评论列表长度小于150，则继续滚动
                  console.log(`当前评论条数【${commentList.length}】, 还未超过150条，继续执行滚动`)
                  await scrollIntoView({page, selector: 'footer[data-e2e="page-footer"]', totalSeconds: 1});
                } else {
                  console.log("获取评论结束，执行返回操作");
                  resolve(commentList);
                }
              })
              .catch((error) => {
                console.error('Error occurred when processing response.json():', error);
              });
        }
      });
    })

    // console.log('滚动结束，开始找元素')
    //
    // // 在评论列表元素内查找所有 data-e2e="comment-item" 的元素
    // const commentItems = await commentListHandle.$$(douyinCommentSelector.commentItem);
    //
    // const commentInfoList = []
    //
    // for (const commentItem of commentItems) {
    //   // 获取昵称、头像、评论内容的元素句柄
    //   const nickNameElement = await commentItem.$(douyinCommentSelector.nickName)
    //   const avatarElement = await commentItem.$(douyinCommentSelector.avatar)
    //   const commentElement = await commentItem.$(douyinCommentSelector.comment)
    //   // 获取具体昵称、头像、评论内容
    //   const nickName = await nickNameElement?.evaluate(element => element.textContent)
    //   const avatar = await avatarElement?.evaluate(element => element.src)
    //   const comment = await commentElement?.evaluate(element => {
    //     let children = element.childNodes
    //     let content = ""
    //     children.forEach(child => {
    //       // 如果当前元素是img
    //       if (child.nodeName === 'IMG') {
    //         // 获取alt属性
    //         let alt = child.getAttribute('alt')
    //         content = content + alt
    //       }
    //       if (child.nodeName === 'SPAN') {
    //         content = content + child.textContent
    //       }
    //     })
    //     return content
    //   })
    //   // if (nickName && avatar && comment) {
    //   //   commentInfoList.push({
    //   //     nickName,
    //   //     avatar,
    //   //     comment
    //   //   })
    //   // }
    //   commentInfoList.push({
    //     nickName,
    //     avatar,
    //     comment
    //   })
    // }
    // return {commentInfoList, commentList}

  } catch (e) {
    console.error('报错', e)
  }
})

ipcMain.handle('douyin:comment:giveALike', async (event, args) => {
  let {webviewId, homePageId} = args
  const spider = new Spider()
  let page = await spider.connect_webview(webviewId)
  await page.evaluate((homePageId) => {
    // 找到用户指定用户的评论
    let user = document.querySelector(`.comment-item-info-wrap a[href="//www.douyin.com/user/${homePageId}"]`)
    user.scrollIntoView({
      behavior:'smooth'
    });
    // 执行点赞动作
    const target = user.closest('div[data-e2e="comment-item"]').querySelector('.xZhLomAs')
    if (target.classList.contains(".ghHVtRBm")) {
      console.log("已存在点赞，跳过点赞")
    } else {
      target.click()
    }
  }, homePageId)
})

ipcMain.handle('douyin:comment:comment', async (event, args) => {
  try {
    let {webviewId, homePageId, content} = args
    const spider = new Spider()
    let page = await spider.connect_webview(webviewId)

    page.on('response', async (response) => {
      if (response.url().indexOf('https://www.douyin.com/aweme/v1/web/comment/publish') !== -1) {
        try {
          const res = await response.json()
          if (res.status_code === 0) {
            app.mainWindow.webContents.send('comment-publish-succeed', JSON.stringify(res))
          }
        } catch (e) {
          console.error('发送失败，需要验证', e)
        }
      }
    })

    // 等待用户元素出现
    let user = await page.waitForSelector(`.comment-item-info-wrap a[href="//www.douyin.com/user/${homePageId}"]`);

    await user.evaluate(userHandle => {
      userHandle.scrollIntoView({ behavior:'smooth' });
    });

    // 找到父元素 div[data-e2e="comment-item"]
    let parentDiv = await user.evaluateHandle(userHandle => {
      return userHandle.closest('div[data-e2e="comment-item"]');
    });

    // 找到目标元素.goxvCv28.fjGrSeaB
    let target = await parentDiv.$('.goxvCv28.fjGrSeaB');
    if (target) {
      // 点击目标元素
      await target.click();
    } else {
      console.error('没有找到点击评论目标元素');
    }

    await new Promise(resolve => {setTimeout(resolve, 1000)})

    // 找到评论输入框并输入内容
    let richtextContainer = await page.waitForSelector('.richtext-container');
    if (richtextContainer) {
      await page.type('.richtext-container', ' [比心] ');
      // todo 会不会拿不到这个按钮
      let sendButton = await parentDiv.$('.WFB7wUOX.NUzvFSPe');
      if (sendButton) {
        await sendButton.click();
      } else {
        console.error('没有找到发送按钮');
      }
    } else {
      console.error('没有找到输入评论的容器元素');
    }
  } catch (e) {
    console.error('报错', e)
  }


  // await page.evaluate((homePageId, content) => {
  //   // 找到用户指定用户的评论
  //   let user = document.querySelector(`.comment-item-info-wrap a[href="//www.douyin.com/user/${homePageId}"]`)
  //   user.scrollIntoView({
  //     behavior:'smooth'
  //   });
  //   // 执行评论动作
  //   target = user.closest('div[data-e2e="comment-item"]').querySelector('.goxvCv28.fjGrSeaB')
  // }, homePageId, content)
  //
  // await page.click(target)
  //
  // await page.type('.richtext-container', 'Hello');
})

ipcMain.handle('douyin:home:page', async (event, args) => {
  let {webviewId, cookiesArray} = args
  let cookies = JSON.parse(cookiesArray)
  const pptr = new PuppeteerWebview()
  await pptr.connectWebview(webviewId, cookies)
  if (!pptr.page) {
    console.error("webview not found")
    return []
  }
  await pptr.goto('https://www.douyin.com/user/MS4wLjABAAAA0bzjQz773w_gNg-tmXbXpG-oMQIxAhoqG41G9UewwJE')
  pptr.page.addStyleTag({content: 'body {zoom: 0.7;}'})
})

ipcMain.handle('douyin:home:follow', async (event, args) => {
  let {webviewId, homePageId, cookiesArray} = args
  let cookies = JSON.parse(cookiesArray)
  const pptr = new PuppeteerWebview()
  await pptr.connectWebview(webviewId, cookies)
  if (!pptr.page) {
    console.error("webview not found")
    return {code: 404, data: '找不到页面'}
  }
  await pptr.goto(`https://www.douyin.com/user/${homePageId}`)
  pptr.page.addStyleTag({content: 'body {zoom: 0.7;}'})
  try {

    // 等待目标按钮元素加载
    let followButtonHandle = await pptr.wait_dom({waitSelector: 'button[data-e2e="user-info-follow-btn"]', desc: '等待关注按钮加载'});

    // 在页面上下文中执行代码获取元素文本内容
    const buttonText = await pptr.page.$eval('button[data-e2e="user-info-follow-btn"] .semi-button-content', (element) => {
      return element.innerText;
    });

    console.log('按钮文本内容:', buttonText);

    if (buttonText === '已关注') {
      return {code: 500, data: '已关注过该用户'}
    }
    if (buttonText === '相互关注') {
      return {code: 500, data: '已经是相互关注'}
    }
    if (buttonText === '回关') {
      await followButtonHandle.click()
      return {code: 200, data: '关注成功'}
    }
    if (buttonText === '关注') {
      await followButtonHandle.click()
      return {code: 200, data: '关注成功'}
    }

    return {code: 500, data: '未知错误'}
  } catch (e) {
    console.error('关注失败：', e)
    return {code: 500, data: '关注失败'}
  }
})

ipcMain.handle('douyin:home:privateMessage', async (event, args) => {
  let {webviewId, homePageId, cookiesArray} = args
  let cookies = JSON.parse(cookiesArray)
  const pptr = new PuppeteerWebview()
  await pptr.connectWebview(webviewId, cookies)
  if (!pptr.page) {
    console.error("webview not found")
    return {code: 404, data: '找不到页面'}
  }
  await pptr.goto(`https://www.douyin.com/user/${homePageId}`)
  pptr.page.addStyleTag({content: 'body {zoom: 0.7;}'})
  try {

    // 等待私信按钮元素加载
    let privateMessageButtonHandle = await pptr.wait_dom({waitSelector: '.K8kpIsJm.IoBgzsYj.dGq2GnTL', desc: '等待私信按钮元素加载'});

    // 点击并等待私信输入框出现
    let privateMessageInputHandle = await pptr.click_wait_dom({handle: privateMessageButtonHandle, waitSelector: '.im-richtext-container', desc: '点击私信并等待私信输入框出现'})

    await pptr.write({handle: privateMessageInputHandle, content: 'Hello World', desc: '输入私信内容'})

    await pptr.wait_dom_click({waitSelector: '.e2e-send-msg-btn', desc: '等待私信发送按钮出现后并点击'})

    // await privateMessageInputHandle.type('Hello World')

  } catch (e) {
    console.error('私信失败：', e)
    return {code: 500, data: '私信失败'}
  }
})
